<?php

/* 访问控制 */
defined('IN_ECTOUCH') or die('Deny Access');

class StoreModel extends BaseModel {

    protected $table = 'store';

    function get_store_info($store_id) {
        $time = gmtime();
        $sql = "SELECT * FROM " . $this->pre . "store WHERE id = '$store_id'";
        $row = $this->row($sql);

        if ($row !== false) {
            return $row;
        } else {
            return false;
        }
    }

	/**
     * 获取推荐店铺
     * @param  $limit
     * @param  $start
     */
    public function store_list($lng, $lat, $distance = 1, $limit = 10, $start = 0) {
		define(EARTH_RADIUS, 6371); //地球半径，平均半径为6371km

		$squares = $this->returnSquarePoint($lng, $lat, $distance, EARTH_RADIUS);

        $sql = "SELECT * FROM " . $this->pre . "store AS s LEFT JOIN " . $this->pre . "region AS r ON s.id_dist = r.region_id ";
		//$sql .= " WHERE r.region_type = 3 and s.lat<>0 and s.lat>".$squares['right-bottom']['lat']." and lat<".$squares['left-top']['lat']." and lng>".$squares['left-top']['lng']." and lng<".$squares['right-bottom']['lng'];
		$sql .= ' ORDER BY ACOS(SIN(('.$lat.' * 3.1415) / 180 ) * SIN((s.lat * 3.1415) / 180 ) + COS(('.$lat.' * 3.1415) / 180 ) * COS((s.lat * 3.1415) / 180 ) * COS(('.$lng.'* 3.1415) / 180 - (s.lng * 3.1415) / 180 ) ) * ' . EARTH_RADIUS . ' asc limit ' . $start . ', ' . $limit;
        $result = $this->query($sql);

		foreach($result as $_k=>$_v){
			 $result[$_k]['store_img'] = get_image_path($_v['id'], $_v['store_img']);
		}

        return $result ? $result : $this->query("SELECT * FROM " . $this->pre . "store limit " . $start . ", " . $limit);
    }

	/**
	 *计算某个经纬度的周围某段距离的正方形的四个点
	 *
	 *@param lng float 经度
	 *@param lat float 纬度
	 *@param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为1千米
	 *@return array 正方形的四个点的经纬度坐标
	 */
	public function returnSquarePoint($lng, $lat, $distance = 1, $earth_radius = 6371){
		$dlng = 2 * asin(sin($distance / (2 * $earth_radius)) / cos(deg2rad($lat)));
		$dlng = rad2deg($dlng);

		$dlat = $distance / $earth_radius;
		$dlat = rad2deg($dlat);

		return array(
					'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng - $dlng),
					'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
					'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
					'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
				);
	}

}
